package com.tian.view.anim.custom

import android.graphics.Camera
import android.view.animation.Animation
import android.view.animation.Transformation

/**
 * @author tiansongtao
 * @date 2023/4/10 9:30
 */
class Rotate3dAnimation(val mFromDegrees: Float, val mEndDegrees: Float, var reverse: Boolean) : Animation() {


    private val mReverse: Boolean = reverse
    private lateinit var mCamera: Camera
    private var mCenterX = 0f
    private var mCenterY = 0f
    private val mDepthZ = 400f


    override fun initialize(width: Int, height: Int, parentWidth: Int, parentHeight: Int) {
        super.initialize(width, height, parentWidth, parentHeight)
        mCamera = Camera()
        mCenterX = width.toFloat() / 2
        mCenterY = height.toFloat() / 2
    }


    override fun applyTransformation(interpolatedTime: Float, t: Transformation?) {
        val degrees = mFromDegrees + ((mEndDegrees - mFromDegrees) * interpolatedTime)
        mCamera.save()
        var z = 0f
        if (mReverse) {
            z = mDepthZ * interpolatedTime
            mCamera.translate(0.0f, 0.0f, z)
        } else {
            z = mDepthZ * (1f - interpolatedTime)
            mCamera.translate(0.0f, 0.0f, z)
        }
        val matrix = t?.matrix
        mCamera.rotateY(degrees)
        mCamera.getMatrix(matrix)
        mCamera.restore()
        matrix?.preTranslate(-mCenterX, -mCenterY)
        matrix?.postTranslate(mCenterX, mCenterY)
        super.applyTransformation(interpolatedTime, t)

    }



}